package org.langqiao.experiment.experiment10;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.Statement;

import javax.swing.*;
import java.sql.*;
public class AddDialog extends JDialog implements ActionListener{
	private JButton add,reset;
	private JLabel label[];
	private JTextField textField[];
	private String sql,str[];
	
	AddDialog(JFrame f,String title,boolean model){
		super(f,title,model);
		this.setBounds(f.getX()+50, f.getY()+50, 200, 230);
		this.setLayout(new FlowLayout());
		String stInfo[]={"学号：","姓名：","性别：","专业：","年龄："};
		String courseInfo[]={"课程号：","课程名：","学分："};
		String scoreInfo[]={"学号：","课程号：","成绩："};
		str=scoreInfo;
		sql="insert into ";
		if(title.equals("学生信息")){
			str=stInfo;
			sql+="student values (";
//System.out.println(str[0]);
		}
		if(title.equals("课程信息")){
			str=courseInfo;
			sql+="course values (";
		}
		if(title.equals("学生成绩信息")){
			str=scoreInfo;
			sql+="score values (";
		}
		label=new JLabel[str.length];
		textField=new JTextField[str.length];
		for(int i=0;i<str.length;i++){
			label[i]=new JLabel(str[i]);
			textField[i]=new JTextField(10);
			this.getContentPane().add(label[i]);
			this.getContentPane().add(textField[i]);
		}
		add=new JButton("添加");
		reset=new JButton("重置");
		add.addActionListener(this);
		reset.addActionListener(this);
		this.add(add);
		this.add(reset);
		this.setDefaultCloseOperation(HIDE_ON_CLOSE);
		this.setVisible(true);
	}
	
	public void actionPerformed(ActionEvent e) {
		if(e.getActionCommand().equals("添加")){
			String sql1=sql;
			for(int i=0;i<str.length;i++)
				sql1+="'"+textField[i].getText()+"',";
			sql1=sql1.substring(0,sql1.length()-1);
			sql1+=")";
System.out.println(sql1);
			try {
				addToDataBase(sql1);
			} catch (Exception e1) {
				JOptionPane.showMessageDialog(this, "插入数据错误！");
			}
		}
		else if(e.getActionCommand().equals("重置")){
			for(int i=0;i<str.length;i++)
				textField[i].setText("");
		}
	}

	private void addToDataBase(String sql) throws Exception{
		Class.forName("com.mysql.jdbc.Driver");
		String URL="jdbc:mysql://localhost:3308/stuInfor?user=root&password=123456";
		Connection conn=DriverManager.getConnection(URL);
		//String sql="select * from "+table;
		Statement stmt=conn.createStatement();
		stmt.executeUpdate(sql);
		stmt.close();
		conn.close();
		
	}
	
}
